<template>
  <view>
    <view class="header">
      <view class="date-time-box">
        <uni-datetime-picker v-if="isReload" type="daterange" returnType="timestamp" :clear-icon="false"
          v-model="timeRange" @change="timeChange" />
      </view>
      <button type="primary" @click="resetQuery()">
        重置
      </button>
      <button type="primary" plain @click="moreQuery()">
        更多查询
      </button>
    </view>
    <view class="overview">
      <view v-for="(list,index) in overviewList" :key="index">
        <view v-for="(item,ind) in list" :key="ind">
          <view class="value">{{item.value}}</view>
          <view class="label">{{item.label}}</view>
        </view>
      </view>
    </view>
    <view class="table" v-for="(item,index) in list" :key="index">
      <view class="title">
        <text>{{item.title}}</text>
      </view>
      <expand-table :uniqueKey="'id'" :signKey="'riseDeficientTon'" :headerList="headerList"
        :dataSource="item.dataSource"></expand-table>
    </view>
    <more-search ref="moreSearchRef" :show="showMore" :isShowCustomer="false" :isShowProduct="false"
      :multipleSearch="true" :supplierList="supplierList" :coalTypeList="productList" @closePop="closePop"
      @filterChange="filterChange"></more-search>
  </view>
</template>
<script>
  import { toast } from '@/utils/common';
  import { getCustListsPage } from '@/api/paihao';
  import moreSearch from '../common/more-search/more-search.vue'
  import { timestampToChineseDate, getUnitConversionData } from '@/utils/common'
  import { getStatisticsTotal, getStatisticsPageForEnterprise, getProductListBySupplier } from '@/api/reportTable';
  export default {
    components: {
      moreSearch
    },
    data() {
      return {
        isReload: true,
        showMore: false,
        supplierList: [],
        productList: [],
        timeRange: [],
        isMore: 'more',
        total: 0,
        params: {
          pageNo: 1,
          pageSize: 10
        },
        queryParam: {
          smallProgramType: 2,
          startTime: '',
          endTime: '',
          supplierIdList: [],
          productIdList: [],
          statisticsTimeType: 10
        },
        overview: {
          totalWeight: 0,
          carNumber: 0,
          goodsSettlementAmount: 0,
          mineralNetWeight: 0,
          deficientTon: 0,
          riseTon: 0
        },
        labelMap: {
          totalWeight: '站收净重(吨)',
          carNumber: '车数',
          goodsSettlementAmount: '货款金额(元)',
          mineralNetWeight: '矿发净重(吨)',
          deficientTon: '亏吨(吨)',
          riseTon: '涨吨(吨)'
        },
        overviewList: [],
        headerList: [
          {
            label: '供应商',
            fixed: true,
            align: 'flex-start',
            width: '210rpx',
            dataKey: 'supplierName'
          }, {
            label: '产品',
            dataKey: 'productName'
          }, {
            label: '站收净重',
            dataKey: 'totalWeight'
          }, {
            label: '矿发净重',
            dataKey: 'mineralNetWeight'
          }, {
            label: '车数',
            dataKey: 'carNumber'
          }, {
            label: '金额',
            dataKey: 'goodsSettlementAmount'
          }, {
            label: '亏/涨吨',
            dataKey: 'riseDeficientTon'
          }
        ],
        list: []
      }
    },
    onShow() {
      this.getSupplierList()
      this.getProductList()
      this.initTimeRange()
    },
    onPullDownRefresh() {
      this.initPageData()
    },
    onReachBottom() {
      if (this.isMore == 'more') {
        this.params.pageNo++;
        this.getStatisticsPageForCX();
      }
    },
    methods: {
      initTimeRange() {
        this.isReload = false
        const ONE_DAY = 24 * 3600 * 1000;
        const CURRENT_DAY = new Date().getTime()
        const YESTERDAY = new Date().getTime() - ONE_DAY
        this.queryParam.startTime = timestampToChineseDate(YESTERDAY)
        this.queryParam.endTime = timestampToChineseDate(CURRENT_DAY)
        setTimeout(() => {
          this.isReload = true
          this.timeRange = [YESTERDAY, CURRENT_DAY]
          this.initPageData()
        }, 0)
      },
      resetQuery() {
        this.queryParam = {
          smallProgramType: 2,
          startTime: '',
          endTime: '',
          supplierIdList: [],
          productIdList: [],
          statisticsTimeType: 10
        }
        this.$refs.moreSearchRef.resetFilter()
        this.initTimeRange()
      },
      moreQuery() {
        this.showMore = true;
      },
      timeChange() {
        const LIMIT = 100 * 24 * 3600 * 1000;
        if (this.timeRange[1] - this.timeRange[0] > LIMIT) {
          toast('最大查询100天数据')
          return
        }
        this.queryParam.startTime = timestampToChineseDate(this.timeRange[0])
        this.queryParam.endTime = timestampToChineseDate(this.timeRange[1])
        this.initPageData()
      },
      closePop() {
        this.showMore = false
      },
      filterChange(data) {
        this.queryParam.statisticsTimeType = data.timeType
        this.queryParam.supplierIdList = data.supplier
        this.queryParam.productIdList = data.coalType
        this.showMore = false
        this.initPageData()
      },
      async getSupplierList() {
        const res = await getCustListsPage();
        if (res.code == 0) {
          const result = res.data || [];
          this.supplierList = result.map(e => {
            return {
              value: e.id,
              checked: false,
              label: e.supplierAbbreviation || e.customerName
            }
          })
        }
      },
      async getProductList() {
        const res = await getProductListBySupplier();
        if (res.code == 0) {
          const result = res.data || [];
          this.productList = result.map(e => {
            return {
              value: e.id,
              checked: false,
              label: e.proName
            }
          })
        }
      },
      initPageData() {
        this.list = [];
        this.isMore = 'more';
        this.params.pageNo = 1
        this.getStatisticsTotal()
        this.getStatisticsPageForEnterprise()
      },
      async getStatisticsTotal() {
        const res = await getStatisticsTotal(this.queryParam)
        if (res.code === 0) {
          let list = [];
          this.overviewList = [];
          const result = res.data || {}
          Object.keys(this.overview).forEach((key, index) => {
            this.overview[key] = result[key] || 0
            list.push(getUnitConversionData(key, result[key], this.labelMap))
            if (index % 3 === 2) {
              this.overviewList.push(list)
              list = []
            }
          })
        } else {
          toast(res.msg)
        }
      },
      async getStatisticsPageForEnterprise() {
        const data = { ...this.params, ...this.queryParam }
        const res = await getStatisticsPageForEnterprise(data)
        if (res.code === 0) {
          const result = res.data || {}
          const list = this.handleList(result.list || [])
          const total = result.total || 0
          this.list = [...this.list, ...list]
          if (result.total == this.list.length) {
            this.isMore = 'noMore';
          }
        } else {
          toast(res.msg)
        }
        wx.stopPullDownRefresh();
      },
      handleList(list) {
        return list.map(e => {
          const obj = e.statisticsRespVO
          obj['expanded'] = false
          const supplierList = this.handleChildren(e.purchaseStatisticsRespTreeVOList || [])
          return {
            title: `中转客户：${obj.purchaseName || '-'}`,
            dataSource: [obj, ...supplierList]
          }
        })
      },
      handleChildren(list) {
        return list.map(e => {
          e['expanded'] = false
          return e
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .header {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    background-color: #ffffff;

    .date-time-box {
      flex: 1;
      margin-left: 20rpx;
      background-color: #F1F2F5;
    }
  }

  button {
    margin-left: 10rpx;
    border: 0 !important;
    padding: 10rpx 20rpx;
    font-size: 24rpx !important;
  }

  button[type="primary"] {
    background: #409efe !important;
  }

  button[plain] {
    margin-right: 20rpx;
    color: #409EFE !important;
    background: #E0EFFF !important;
  }

  .overview {
    padding: 40rpx 20rpx;
    margin: 20rpx 20rpx 0 20rpx;
    background: linear-gradient(103deg, #1fbcff 0%, #4a72ff 100%);
    border-radius: 8rpx;
    color: #ffffff;

    >view {
      display: flex;
      align-items: center;

      >view {
        flex: 1;
      }
    }

    >view+view {
      margin-top: 20rpx;
    }

    .value {
      font-size: 40rpx;
      font-weight: 600;
      text-align: center;
    }

    .label {
      font-size: 28rpx;
      text-align: center;
    }
  }

  .table {
    margin: 20rpx 20rpx 0 20rpx;
    background-color: #ffffff;
    border-radius: 8rpx;

    .title {
      font-size: 30rpx;
      font-weight: 600;
      height: 96rpx;
      line-height: 96rpx;
      padding: 0 20rpx;

      text {
        border-left: 4rpx solid #409EFE;
        padding-left: 16rpx;
      }
    }
  }
</style>